#!/usr/bin/perl
#Programmer: Rory Carmichael
#Purpose: Extract the fasta sequences associated with each ortholog group and combine them into one fasta file per group for input into muscle
#Usage: extract_ortholog_groups.pl <group file> <source fasta file> <outputdirectory>

my $groupfile = $ARGV[0];
my $fafile = $ARGV[1];
my $outdir = $ARGV[2];
my $cutoff = $ARGV[3] | 5;
my %fahash = ();
if (!(-d $outdir)) {
	mkdir $outdir;
}

open(FASTA, $fafile);
my $curid;
my $curline;
while (my $line = <FASTA>) {
	if ($line =~ /^>/) {
		$curid = [split(/\s+/,$line)]->[0];
		$fahash{$curid} = tell(FASTA);
#		print "Tagged $curid at $fahash{$curid}\n";
	}
}
print STDERR "LOADED FASTA FILE INTO MEMORY\n";

open(IF, $groupfile);
foreach my $line (<IF>) {
	chomp $line;
	my @splitline = split(/:/, $line);
	my $group = $splitline[0];
	my @members = split(/\s+/,$splitline[1]);
	if($#members >= $cutoff) {
		open(OF, ">$outdir/$group");
		foreach my $seq (@members) {
			my $data;
			if(exists($fahash{">$seq"})) {
				seek(FASTA,$fahash{">$seq"},0);
				$data = <FASTA>;
				print OF ">$seq\n$data";
			}
		}
		close(OF);
	}
}
close(IF);
close(FASTA);
